package com.luoqiz.project.mulThreadDownload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class Downloader {

	private int threadCount = 3;
	private String srcPath;
	private String destPath;
	private long fileLen;
	private List<DownloadInfo> infos = new ArrayList<>();

	public List<DownloadInfo> getInfos() {
		return infos;
	}

	public void setInfos(List<DownloadInfo> infos) {
		this.infos = infos;
	}

	public Downloader(String srcPath, String destPath, int threadCount) {
		this.threadCount = threadCount;
		this.srcPath = srcPath;
		this.destPath = destPath;
		prepareDownload();
	}

	private void prepareDownload() {
		try {
			// 创建新的文件
			URL url = new URL(srcPath);
			HttpURLConnection urlconnect = (HttpURLConnection) url.openConnection();
			fileLen = urlconnect.getContentLengthLong();
			File destFile = new File(destPath);
			File f = new File(destFile.getParentFile(), destFile.getName().substring(0,destFile.getName().lastIndexOf(".")) + ".yundowns");
			System.out.println(f.getAbsolutePath());
			if (f.exists()) {
				getDownloadInfos(f);
			} else {
				RandomAccessFile raf = new RandomAccessFile(destPath, "rw");
				raf.setLength(fileLen);
				raf.close();
				// 计算出下载集合
				initDownloadInfos();
				// 创建下载记录文件
				try {
					f.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
				setDownloadInfosFile(f);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void setDownloadInfosFile(File f) {

		Properties pro = new Properties();
		try {
			pro.load(new FileInputStream(f));
			// 设置线程数
			pro.setProperty("thread.count", threadCount + "");
			pro.setProperty("thread.srcPath", srcPath);
			pro.setProperty("thread.destPath", destPath);
			// 每个线程的信息
			for( DownloadInfo dis:infos) {
				pro.setProperty("thread." + dis.getIndex() + ".startPoint", dis.getStartPoint() + "");
				pro.setProperty("thread." + dis.getIndex() + ".endPoint", dis.getEndPoint() + "");
				pro.setProperty("thread." + dis.getIndex() + ".amount", 0 + "");
			}
			pro.store(new FileOutputStream(f), "Thread Record");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void getDownloadInfos(File file) {
		Properties pro = new Properties();
		try {
			FileInputStream input = new FileInputStream(file);
			pro.load(input);
			threadCount = Integer.parseInt(pro.getProperty("thread.count"));
			for (int i = 0; i < threadCount; i++) {
				DownloadInfo dif = new DownloadInfo();
				dif.setSrcPath(pro.getProperty("thread.srcPath"));
				dif.setDestPath(pro.getProperty("thread.destPath"));
				dif.setIndex(i);
				dif.setStartPoint(Integer.parseInt(pro.getProperty("thread." + i + ".startPoint")));
				dif.setEndPoint(Integer.parseInt(pro.getProperty("thread." + i + ".endPoint")));
				dif.setAmount(Integer.parseInt(pro.getProperty("thread." + i + ".amount")));
				infos.add(dif);
			}
			input.close();
			pro.clear();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void initDownloadInfos() {
		long block = 0l;
		if (fileLen % threadCount == 0) {
			block = fileLen / threadCount;
		} else {
			block = fileLen / threadCount;
		}
		for (int i = 0; i < threadCount; i++) {
			DownloadInfo dlInfo = new DownloadInfo();
			dlInfo.setIndex(i);
			dlInfo.setSrcPath(srcPath);
			dlInfo.setDestPath(destPath);
			dlInfo.setStartPoint(i * block);
			if (i == threadCount - 1) {
				dlInfo.setEndPoint(fileLen);
			} else {
				dlInfo.setEndPoint((i + 1) * block - 1);
			}

			infos.add(dlInfo);
		}

	}

	public void start() {
		DownloaderThread.setDown(true);
		File destFile = new File(destPath);
		File f = new File(destFile.getParentFile(),
				destFile.getName().substring(0, destFile.getName().lastIndexOf(".")) + ".yundowns");
		System.out.println(f.getAbsolutePath());
		Properties pro = new Properties();
		FileInputStream input;
		try {
			input = new FileInputStream(f);
			pro.load(input);
			for (DownloadInfo dlfo : infos) {
				new DownloaderThread(dlfo,pro).start();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void pause() {
		DownloaderThread.setPause(!DownloaderThread.isPause());
	}

	public void end() {
		DownloaderThread.setDown(false);
	}
}
